/*
 * Copyright 2020-2025 the original author or authors.
 * You cannot use this file unless authorized by the author.
 */

package org.ipig.commons.helper;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * ClassLoaderHelper
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id: ClassLoaderHelper.java 3 2020-01-21 09:36:33Z ts <comchnts@163.com> $$
 * @since 1.0
 */
public class ClassLoaderHelper {
    /**
     * getResource
     * @param resourceName
     * @param callingClass
     * @return
     */
    public static URL getResource(String resourceName, Class callingClass) {
        URL url = null;
        url = Thread.currentThread().getContextClassLoader().getResource(
                resourceName);
        if (url == null) {
            url = ClassLoaderHelper.class.getClassLoader().getResource(
                    resourceName);
        }
        if (url == null) {
            url = callingClass.getClassLoader().getResource(resourceName);
        }
        return url;
    }

    /**
     * getResourceAsStream
     * @param resourceName
     * @param callingClass
     * @return
     */
    public static InputStream getResourceAsStream(String resourceName,
                                                  Class callingClass) {
        URL url = getResource(resourceName, callingClass);
        try {
            return (url != null) ? url.openStream() : null;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * loadClass
     * @param className
     * @param callingClass
     * @return
     * @throws ClassNotFoundException
     */
    public static Class loadClass(String className, Class callingClass)
            throws ClassNotFoundException {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(
                    className);
        } catch (ClassNotFoundException e) {
            try {
                return Class.forName(className);
            } catch (ClassNotFoundException ex) {
                try {
                    return ClassLoaderHelper.class.getClassLoader()
                            .loadClass(className);
                } catch (ClassNotFoundException exc) {
                    return callingClass.getClassLoader().loadClass(className);
                }
            }
        }
    }
}
